﻿using System;
using System.Data.SqlClient;

namespace Daco.Data
{
    public interface IDbConnectionManager
    {
        string ConnectionString
        {
            get;
        }

        SqlConnection DBConnection
        {
            get;
        }

        SqlConnection OpenDBConnection
        {
            get;
        }

        void InitConnection();

        void CloseConnection();
    }
    public class CDbConnectionManager : IDbConnectionManager, IDisposable
    {
        protected SqlConnection _connection = null;

        #region IConnectionManager Members

        virtual public string ConnectionString
        {
            get
            {
                return Core.CBaseConfig.Current.ConnectionString;
            }
        }

        public SqlConnection DBConnection
        {
            get
            {
                InitConnection();
                return _connection;
            }
        }

        public SqlConnection OpenDBConnection
        {
            get
            {
                InitConnection();
                if (_connection.State != System.Data.ConnectionState.Open)
                    _connection.Open();
                return _connection;
            }
        }

        public CDbConnectionManager()
        {
            InitConnection();
        }

        public void InitConnection()
        {
            if (_connection == null)
            {
                _connection = new SqlConnection(this.ConnectionString);
            }
            else if (_connection.State != System.Data.ConnectionState.Open)
            {
                _connection.ConnectionString = this.ConnectionString;
            }
        }

        public void CloseConnection()
        {
            if (_connection != null && _connection.State == System.Data.ConnectionState.Open)
                _connection.Close();
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            if (_connection != null)
            {
                CloseConnection();
                _connection = null;
            }
        }

        #endregion
    }
}
